# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: write_data_2_csv.py
  @time: 2021/3/2 12:04
  @desc:
"""

from PySide6.QtCore import *

import openpyxl
from openpyxl.styles import Font
from gui import constant


class Signal(QObject):
    write_state = Signal(int)


class WriteData2CSV(QRunnable):
    def __init__(self, file_path, table_data, header_info):
        super(WriteData2CSV, self).__init__()
        self.signal = Signal()
        self.file_path = file_path

        self.header_info = header_info
        self.table_data = table_data
        self.flag = True

    def run(self):
        global work
        try:
            work = openpyxl.load_workbook(constant.TEMPLATE_PATH)  # 打开一个工作簿
            ft1 = Font(name='Arial', size=9)
            sheet_names = work.get_sheet_names()  # 获得sheet_name的数组
            sheet1 = work.get_sheet_by_name('sample')  # 以sheet名称获取sheet对象
            sheet2 = work.get_sheet_by_name(sheet_names[0])  # 获取名称数组后按索引，可以在不知道名称的情况下遍历
            if self.basic_info:
                sheet1.cell(8, 2).value = self.basic_info[4]  # 需要注意的是单元格从1，1开始，而不是0
                sheet1.cell(9, 2).value = self.basic_info[8]
            if self.equip_info:
                for i in range(len(self.equip_info)):
                    for j in range(len(self.equip_info[i])):
                        sheet1.cell(18 + i, 2 * j + 2).value = self.equip_info[i][j]  # 需要注意的是单元格从1，1开始，而不是0

            if self.header_info:
                for e in range(len(self.header_info)):
                    sheet1.cell(26, e + 1).value = self.header_info[e]
            if self.table_data:
                for t in range(len(self.table_data)):
                    for k in range(len(self.table_data[t])):
                        sheet1.cell(27 + t, k + 1).value = self.table_data[t][k]
            work.save(f'{self.file_path}')  # 保存更名
        except PermissionError as e:
            logger.error("WriteData2CSV," + str(e))
            self.signal.write_state.emit(2)
        except Exception as e:
            logger.error("WriteData2CSV," + str(e))
            self.signal.write_state.emit(0)
        else:
            self.signal.write_state.emit(1)
        finally:
            work.close()
